import { connection } from '../app/database/mysql'
import { UserModel } from './user.model'

export const createUser = async (user: UserModel) => {
  const statement = `INSERT INTO USER SET ?`
  const [data] = await connection.promise().query(statement, [user])
  return data
}

export const getUser = (condition: string): any => {
  return async (params: string, options: any) => {
    const statement = `
      SELECT 
        user.id, 
        user.name,
        CASE WHEN COUNT(avatar.id) > 0 THEN 1 ELSE NULL END AS avatar
        ${options?.password ? ', password' : ''}
      FROM user
      LEFT JOIN avatar ON user.id = avatar.user_id
      WHERE ${condition} = ?
      GROUP BY user.id, user.name;
    `

    const [data] = (await connection.promise().query(statement, params)) as any

    return data?.[0]
  }
}

export const getUserByName = getUser('user.name')
export const getUserById = getUser('user.id')

export const updateUser = async (id: number, user: UserModel) => {
  const statement = `UPDATE USER SET ? WHERE id = ?`

  const [data] = await connection.promise().query(statement, [user, id])
  return data
}
